package cn.tx.coolshark.controller;

import cn.tx.coolshark.mapper.UserMapper;
import cn.tx.coolshark.pojo.dto.UserDto;
import cn.tx.coolshark.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/login")
    //当客户端是post请求，并且提交的是JS对象时在接收参数前使用@RequestBody注解
    //否则接收的是null
    public int login(@RequestBody  UserDto userDto, HttpServletResponse response, HttpSession session){
        System.out.println("userDto = " + userDto);
        UserVO user = userMapper.selectByUsername(userDto.getUsername());
        if(user!=null){
            if(user.getPassword().equals(userDto.getPassword())){
                //判断是否需要记住用户名和密码
                if(userDto.getRem()){
                    //创建cookie对象，把用户名和密码装进去
                    Cookie c1 = new Cookie("username",userDto.getUsername());
                    Cookie c2 =new Cookie("password",userDto.getPassword());
                    //设置保存时长
                    c1.setMaxAge(60*60*24*30);
                    c2.setMaxAge(60*60*24*30);
                    //把cookie响应给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                //把当前登录成功的UserVO存到session对象中
                session.setAttribute("user",user);
                return 1;
            }
            return 2;
        }
        return 3;
    }
    @RequestMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO) session.getAttribute("user");
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
